/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 百世官方接口上传网点
 *  */

import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { Button, message, Input, Popconfirm } from 'antd';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import { getHTStations, addHTStation, delHTStation } from '@/services/cityXLS';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { HTTableListItem } from './HTUpload.d';
import { useLocation, useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';
import styles from './HTUpload.less';

const HTUpload: React.FC = () => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const [submitting, setSubmitting] = useState(false);
  const { pathname } = useLocation();
  const brand = pathname.split('/').pop() || '';
  const brands = {
    htUpload: '是否通过官方接口上传',
    ytUpload: '是否通过尊者PC端接口上传到件并上传图片',
    jtUpload: '添加时间',
  };

  const handleDelete = (data: HTTableListItem) => {
    const { id, branch_no } = data;
    delHTStation({ id, branch_no }, brand).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success('操作成功');
        actionRef.current?.reload();
      } else {
        message.error(msg);
      }
    });
  };
  const columns: ProColumns<HTTableListItem>[] = [
    {
      title: '网点编号',
      dataIndex: 'branch_no',
      align: 'center',
      renderFormItem: () => {
        return <Input placeholder='请输入网点编号' />;
      },
    },
    {
      title: '网点名称',
      dataIndex: 'branch_name',
      align: 'center',
      search: false,
    },
    {
      title: brands[brand],
      dataIndex: 'is_open',
      hideInTable: brand === 'jtUpload',
      align: 'center',
      search: false,
      valueEnum: {
        '1': '是',
        '0': '否',
      },
    },
    {
      title: brands[brand],
      dataIndex: brand === 'jtUpload' ? 'create_time' : 'create_at',
      hideInTable: brand !== 'jtUpload',
      align: 'center',
      search: false,
    },
    {
      title: '操作',
      width: winSize === 'xs' ? 100 : 180,
      valueType: 'option',
      hideInTable: brand !== 'jtUpload',
      align: 'center',
      fixed: 'right',
      search: false,
      render: (_, record) => (
        <Popconfirm title='你确定删除吗？' onConfirm={handleDelete.bind(null, record)}>
          <a>删除</a>
        </Popconfirm>
      ),
    },
  ];

  const fetchTableList = (params: any) => {
    const { current: page, branch_no } = params;
    return getHTStations(
      {
        page,
        branch_no,
        limit: 20,
      },
      brand,
    );
  };

  const onSubmit = async (values: any) => {
    setSubmitting(true);
    const { code, msg } = (await addHTStation(values, brand)) || {};
    setSubmitting(false);
    if (code > 0) {
      message.error(msg);
      return;
    }
    actionRef.current?.reload();
    formRef.current?.resetFields();
  };

  const rules = [
    {
      required: true,
      message: '请输入网点编号',
    },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: '网点编号为字母与数字组成',
    },
  ];

  return (
    <PageContainer className={styles.main}>
      <ProForm
        formRef={formRef}
        layout={winSize === 'xs' ? 'vertical' : 'inline'}
        onFinish={onSubmit}
        submitter={{
          render: (props) => {
            return [
              <Button
                loading={submitting}
                type='primary'
                key='submit'
                onClick={() => props.form?.submit?.()}
              >
                添加
              </Button>,
            ];
          },
        }}
      >
        <ProFormText
          width='md'
          name='branch_no'
          label='网点编号'
          placeholder='请输入网点编号'
          rules={rules}
        />
        <ProFormText
          width='md'
          name='branch_name'
          label='网点名称'
          placeholder='请输入网点名称'
          rules={[
            {
              required: true,
              message: '请输入网点名称!',
            },
          ]}
        />
      </ProForm>
      <DragTable>
        <ProTable<HTTableListItem>
          actionRef={actionRef}
          pagination={{
            pageSize: 20,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          rowKey='id'
          request={fetchTableList}
          columns={columns}
          search={{
            className: 'kb-pro-table-form',
            labelWidth: 'auto',
            collapseRender: () => false,
          }}
          options={false}
          scroll={{ x: 640 }}
        />
      </DragTable>
    </PageContainer>
  );
};

export default HTUpload;
